package com.situ.mall.controller.front;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mall.pojo.entity.Cart;
import com.situ.mall.pojo.entity.User;
import com.situ.mall.pojo.vo.CartListVO;
import com.situ.mall.service.ICartService;
import com.situ.mall.util.JSONResult;

@Controller
@RequestMapping("/cart")
public class FrontCartController {
	@Autowired
	private ICartService cartService;

	@ResponseBody
	@RequestMapping("/insert.shtml")
	public JSONResult insert(Cart cart, HttpSession session) {
		User user = (User) session.getAttribute("user");
		cart.setUserId(user.getId());
		cart.setChecked(1);
		boolean isSuccess = cartService.insertCart(cart);
		return isSuccess == true ? JSONResult.success("加入购物车成功") : JSONResult.error("加入失败");
	}

	@RequestMapping("/getCartPage.shtml")
	public String getDetailPage(HttpSession session, Model model) {
		User user = (User) session.getAttribute("user");
		List<CartListVO> list = cartService.selectByUser(user.getId());
		if (list.size() == 0) {
			return "front/cart-empty";
		}
		model.addAttribute("list", list);
		return "front/cart";
	}

	@ResponseBody
	@RequestMapping("/updateQuantity.shtml")
	public JSONResult updateQuantity(Integer productId, Integer quantity, HttpSession session) {
		User user = (User) session.getAttribute("user");
		boolean isSuccess = cartService.updateQuantity(productId, quantity, user.getId());
		return isSuccess == true ? JSONResult.success("修改成功") : JSONResult.error("修改失败");
	}

	@ResponseBody
	@RequestMapping("/deleteById.shtml")
	public JSONResult deleteById(Integer cartId) {
		boolean isSuccess = cartService.deleteById(cartId);
		return isSuccess == true ? JSONResult.success("删除成功") : JSONResult.error("删除失败");
	}

	@ResponseBody
	@RequestMapping("/updateStatus.shtml")
	public JSONResult updateStatus(Integer cartId, Integer checked) {
		boolean isSuccess = cartService.updateStatus(cartId, checked);
		return isSuccess == true ? JSONResult.success() : JSONResult.error();
	}

	@ResponseBody
	@RequestMapping("/updateStatusAll")
	public JSONResult checkall(HttpSession session, Integer checkedall) {
		User user = (User) session.getAttribute("user");
		boolean isSuccess = cartService.updateStatusAll(user.getId(), checkedall);
		return isSuccess == true ? JSONResult.success() : JSONResult.error();
	}
}
